package com.service;

import com.dao.FrontUserRepository;
import com.model.FrontUser;
import com.utils.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class FrontUserService {

    @Resource
    private FrontUserRepository frontUserRepository;

    public boolean checkExists(FrontUser user) {
        return frontUserRepository.existsByUsername(user.getUsername());
    }

    public boolean register(FrontUser user) {
        user.setRegisterTime(LocalDateTime.now());
        user.setPassword(Md5Utils.decodeBackUser(user));
        return frontUserRepository.save(user) != null;
    }

    public FrontUser getByUsername(String username) {
        return frontUserRepository.getByUsername(username);
    }

    public boolean checkPasswordByUser(String password, FrontUser user) {
        String db_md5 = user.getPassword();
        user.setPassword(password);
        String req_md5 = Md5Utils.decodeBackUser(user);
        user.setPassword(db_md5);
        return db_md5.equals(req_md5);
    }

    public boolean updateLoginTime(FrontUser user, LocalDateTime now) {
        return frontUserRepository.updateLoginTimeById(user.getId(), now) >= 1;
    }

    public List<FrontUser> findAll() {
        return frontUserRepository.findAll();
    }
}
